from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from app import db, login_manager
from app.models import User, Asset

bp = Blueprint('main', __name__)

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))

@bp.route('/')
@bp.route('/assets')
def index():
    """显示所有资产的列表"""
    assets = Asset.query.all()
    return render_template('index.html', assets=assets)

@bp.route('/add_asset', methods=['GET', 'POST'])
@login_required
def add_asset():
    """添加资产"""
    if request.method == 'POST':
        # 获取表单数据
        name = request.form['name']
        serial_number = request.form['serial_number']
        asset_type = request.form['asset_type']
        status = request.form['status']
        location = request.form['location']
        assigned_to_id = request.form.get('assigned_to_id')
        
        # 创建新的资产实例
        asset = Asset(
            name=name,
            serial_number=serial_number,
            asset_type=asset_type,
            status=status,
            location=location,
            assigned_to_id=assigned_to_id if assigned_to_id else None
        )
        
        # 添加到数据库
        db.session.add(asset)
        db.session.commit()
        flash('资产添加成功！')
        return redirect(url_for('main.index'))
    
    # GET请求，显示表单
    users = User.query.all()
    return render_template('add_asset.html', users=users)

@bp.route('/edit_asset/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_asset(id):
    """编辑资产"""
    asset = Asset.query.get_or_404(id)
    
    if request.method == 'POST':
        # 更新资产信息
        asset.name = request.form['name']
        asset.serial_number = request.form['serial_number']
        asset.asset_type = request.form['asset_type']
        asset.status = request.form['status']
        asset.location = request.form['location']
        asset.assigned_to_id = request.form.get('assigned_to_id')
        
        # 保存到数据库
        db.session.commit()
        flash('资产更新成功！')
        return redirect(url_for('main.index'))
    
    # GET请求，显示表单
    users = User.query.all()
    return render_template('edit_asset.html', asset=asset, users=users)

@bp.route('/delete_asset/<int:id>', methods=['POST'])
@login_required
def delete_asset(id):
    """删除资产"""
    asset = Asset.query.get_or_404(id)
    db.session.delete(asset)
    db.session.commit()
    flash('资产删除成功！')
    return redirect(url_for('main.index'))

@bp.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录"""
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password):
            login_user(user)
            flash('登录成功！')
            return redirect(url_for('main.index'))
        else:
            flash('用户名或密码错误！')
    
    return render_template('login.html')

@bp.route('/logout')
@login_required
def logout():
    """用户登出"""
    logout_user()
    flash('您已成功登出！')
    return redirect(url_for('main.index'))

@bp.route('/register', methods=['GET', 'POST'])
def register():
    """用户注册"""
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            flash('用户名已存在！')
            return render_template('register.html')
        
        # 创建新用户
        user = User(username=username, email=email)
        user.set_password(password)
        
        # 添加到数据库
        db.session.add(user)
        db.session.commit()
        flash('注册成功！请登录。')
        return redirect(url_for('main.login'))
    
    return render_template('register.html')